import qs from 'qs';
import axios from 'axios';
import {Toast} from 'antd-mobile';
import Constant from './constant';
// const $http =axios.create({baseURL: ""})
const $http =axios.create({baseURL: Constant.host})


$http.interceptors.request.use(config => {
    if(config.headers.showLoading===true){
        Toast.loading('加载数据中....', 15)
    }
  //TODO 验证登录状态
  config.headers.common['CSESSIONID'] = ''
  return config
})
//添加拦截器，提前处理返回的数据
$http.interceptors.response.use((response) => {
  Toast.hide()
  let { data } = response

  if(data.code===1111){
      Toast.info('执行该操作前，需要登录,即将跳转到登录页面！')
      setTimeout(() => {
        window.location = '/paihao';
      }, 1500);
  }
  return data
}, (err) => {
  if (err && err.response) {
      switch (err.response.status) {
          case 400: err.message = '请求错误'
              break
          case 401: err.message = '未授权，请登录'
              break
          case 403: err.message = '拒绝访问'
              break
          case 404: err.message = `请求地址出错: ${err.response.config.url}`
              break
          case 408:
              err.message = '请求超时'
              break
          case 500: err.message = '服务器内部错误'
              break
  
          case 501: err.message = '服务未实现'
              break
          case 502: err.message = '网关错误'
              break
          case 503: err.message = '服务不可用'
              break
          case 504: err.message = '网关超时'
              break
          case 505: err.message = 'HTTP版本不受支持'
              break
          default:
      }
  }
//   Toast.info(err.response.status + err.message)
  return Promise.reject(err)
})

const dataMethodDefault = {
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  },
  withCredentials: true,
  transformRequest: [(data) => qs.stringify(data)],
  timeout: 30000
}


class http {
    constructor(){
        this.config={headers:{showLoading:true}}
    }
    // get请求
    get = (url)=>{
        return $http.get(url, {...this.dataMethodDefault, ...this.config})
    }

    //post请求，默认数据格式json，如需其他配置方式，传入config项
    post = (url,data)=>{
        return $http.post(url,data,{...this.dataMethodDefault, ...this.config})
    }

    // 发送批量请求
    all=(iterable)=>{
        return $http.all(iterable)
    }

    // 设置是否需要显示弹窗
    loadingAble=(showLoading)=>{
        this.config={headers:{showLoading:showLoading}}
        return this
    }

    // 表单请求
    postForm=(url,data)=>{
        return $http.post(url,data,{
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
            },
            withCredentials: true,
            transformRequest: [(data) => qs.stringify(data)],
            timeout: 30000
          })
    }
    
}

export default http;
